"""
异常捕获
"""

# 捕获常规异常
try:
    f = open("D:/python code/abc.txt","r",encoding="UTF-8")
except:
    print("遇到异常，文件未创建")
    f = open("D:/python code/abc.txt", "w", encoding="UTF-8")

# 捕获指定异常
try:
    a = 1/0
except ZeroDivisionError as e:
    print("触发了除0异常")
    print(e)

# 捕获多个异常
try:
    a=1/0
except (ZeroDivisionError,NameError) as e:
    print("出现了变量未定义或者除0异常")
    print(e)

# 捕获所有异常
try:
    print(name)
except Exception as e:
    print("出现了异常")
    print(e)

# else:如果没有异常执行这里（可有可没有）
try:
    print(1)
except:
    print("出现了异常")
else:
    print("没有异常哦")

# finally:无论如何都会执行（不管有没有异常）,（可以用于关闭文件）
try:
    f = open("D:/python code/abc.txt","r",encoding="UTF-8")
except:
    print("遇到异常，文件未创建")
    f = open("D:/python code/abc.txt", "w", encoding="UTF-8")
else:
    print("没有异常哦")
finally:
    print("有没有异常都会执行")
    f.close()


